<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailInfo.visible && !modifyInfoReturn.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
          <template v-slot:filter-useDeptName>
            <slip-select
              v-model="filterInfo.query.queryParams.useDeptIdMult"
              value-key="value"
              placeholder="选择使用部门"
              :api="inOrOutDepotInfo.api"
              key-field="name"
              value-field="id"
              v-model:query="inOrOutDepotInfo.query"
              :clearable="true"
              :filterable="true"
              :multiple="true"
              @change="search"
            />
          </template>
        </NewPageFilter>
      </div>

      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-del>
            <el-button :disabled="!canDel" @click="del()">删除</el-button>
          </template>
          <template v-slot:filter-returnBack>
            <el-button :disabled="!canCancelAudit" @click="returnBackMore()"
              >归还</el-button
            >
          </template>
          <template v-slot:filter-print>
            <PopoverPrint
              ref="popoverShow"
              v-model:popoverVisible="popoverVisible"
              :templateArr="templateArr"
              title="打印"
              :canPrint="$permission('equipmentBorrowingRecord:print')"
              @tempClick="tempClick"
              @print="handelPrint"
            ></PopoverPrint>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowOtherClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-assetName="scope">
          <span class="slip-edit" @click="showProductDetail(scope.row)">
            {{ scope.row.assetName || '-' }}
          </span>
        </template>
      </table-container>
    </div>
    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
    <ModifyReturn
      v-if="modifyInfoReturn.visible"
      v-model:visible="modifyInfoReturn.visible"
      :type="modifyInfoReturn.type"
      :title="modifyInfoReturn.title"
      :data="modifyInfoReturn.row"
      @returnModify="returnModify"
    />
    <!-- 详情页 -->
    <assetCard-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />
    <!-- 明细信息 -->
    <!-- <Detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    /> -->

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <ReturnRegister
      v-if="returnRegisterInfo.visible"
      v-model:showDialog="returnRegisterInfo.visible"
      :options="returnRegisterInfo.options"
      :row="returnRegisterInfo.row"
      title="归还登记"
      @callback="selectMonthCallback"
    />
    <BorrowingRegister
      v-if="borrowingRegisterInfo.visible"
      v-model:showDialog="borrowingRegisterInfo.visible"
      :options="borrowingRegisterInfo.options"
      :row="borrowingRegisterInfo.row"
      title="修改归还登记"
      type="update"
      @callback="updateCallback"
    />
    <PageDialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio label="page">当前页数据</el-radio>
          <el-radio label="all">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
  </div>
</template>

<script setup name="equipmentBorrowingRecord">
import axios from 'axios'
import {
  specialDeleteAssetCard,
  ratifyAssetCardOrder,
  getDepotsSelectAllAndMaintenanceGroup,
  getDeptAll,
} from '@/api/core.js'
import {
  getBorrowRecordPage,
  removeBorrowRecord,
  excelBorrowRecord,
  borrowRecordReturn,
  updateBorrowRecordPut,
} from '@/api/asset.js'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import ReturnRegister from '../../components/returnRegister'
import BorrowingRegister from '../../components/borrowingRegister'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import AssetCardDetail from '@/views/asset/assetManage/assetCard/details'
import { exportTemplateExcel } from '@/api/pub.js'
const Modify = defineAsyncComponent(() => import('./modify'))
const ModifyReturn = defineAsyncComponent(() => import('./modifyReturn'))
const Detail = defineAsyncComponent(() => import('./detail'))
const { proxy } = getCurrentInstance()
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {},
  },
  searchList: [],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('equipmentBorrowingRecord:add'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('equipmentBorrowingRecord:del'),
    },
    {
      type: 'slot',
      value: 'returnBack',
      show: proxy.$permission('equipmentBorrowingRecord:returnBack'),
    },
    {
      type: 'slot',
      value: 'update',
      show: proxy.$permission('equipmentBorrowingRecord:update'),
    },
    /* {
      type: 'button',
      label: '下载模板',
      event: downloadTemplate,
      show: proxy.$permission('equipmentBorrowingRecord:downloadTemplate'),
    }, */
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('equipmentBorrowingRecord:excel'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('equipmentBorrowingRecord:print'),
    },
  ],
})
const returnRegisterInfo = ref({
  visible: false,
  options: [],
  row: {},
})
const borrowingRegisterInfo = ref({
  visible: false,
  options: [],
  row: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '160',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('equipmentBorrowingRecord:update'),
        ifRender: function (row) {
          return [2].includes(row.borrowStatus)
        },
      },
      {
        label: '归还',
        event: returnBack,
        show: proxy.$permission('equipmentBorrowingRecord:returnBack'),
        ifRender: function (row) {
          return [2].includes(row.borrowStatus)
        },
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('equipmentBorrowingRecord:del'),
        ifRender: function (row) {
          return [2].includes(row.borrowStatus)
        },
      },
    ],
  },
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: 'page',
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
//明细相关
const detailInfo = ref({
  visible: false,
  title: '资产档案明细',
  id: '',
})
//新增或更新相关
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
  currentAccountingInterval: '',
  type: '',
  canModifyModule: '',
})
const modifyInfoReturn = ref({
  visible: false,
  title: '',
  id: '',
  currentAccountingInterval: '',
  type: '',
  canModifyModule: '',
})

const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const page = ref({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const canDel = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((item) => [2].includes(item.borrowStatus))
      .length
  )
})
const canCancelAudit = computed(() => {
  return (
    tableInfo.value.selections.length &&
    !tableInfo.value.selections.filter((item) => item.borrowStatus === 3).length
  )
})
let obj = {
  supplierName: {
    label: '供应商',
    value: 'supplierName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'asset_register_status',
    show: false,
    hidden: true,
  },
  assetTypeValue: {
    label: '资产类型',
    value: 'assetTypeValue',
    asValue: 'assetType',
    componentType: 'select-model',
    code: 'asset_type',
    show: false,
    hidden: true,
  },
  increaseTypeValue: {
    label: '增加方式',
    value: 'increaseTypeValue',
    asValue: 'increaseType',
    componentType: 'select-model',
    code: 'increase_type',
    show: false,
    hidden: true,
  },
  deprConventionValue: {
    label: '折旧惯例',
    value: 'deprConventionValue',
    asValue: 'deprConvention',
    componentType: 'select-model',
    code: 'depr_convention',
    show: false,
    hidden: true,
  },
  deprMethodTypeValue: {
    label: '折旧方法',
    value: 'deprMethodTypeValue',
    asValue: 'deprMethodType',
    componentType: 'select-model',
    code: 'depr_method_type',
    show: false,
    hidden: true,
  },
  isLockedValue: {
    label: '是否锁定',
    value: 'isLockedValue',
    asValue: 'isLocked',
    componentType: 'select-model',
    code: 'is_locked',
    show: false,
    hidden: true,
  },
  assetStatusValue: {
    label: '资产状态',
    value: 'assetStatusValue',
    asValue: 'assetStatus',
    componentType: 'select-model',
    code: 'asset_status',
    show: false,
    hidden: true,
  },
  depotName: {
    label: '出库仓库',
    value: 'depotName',
    asValue: 'depotId',
    componentType: 'slip-select',
    query: {
      depotAuth: 'id',
      status: 1,
      useTypeId: '2',
    },
    api: getDepotsSelectAllAndMaintenanceGroup,
    show: false,
    hidden: true,
  },
  useDeptName: {
    label: '使用部门',
    value: 'useDeptName',
    asValue: 'useDeptId',
    query: {
      deptAuth: 'id',
      status: 1,
    },
    api: getDeptAll,
    componentType: 'slip-select',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

const inOrOutDepotInfo = reactive({
  api: getDeptAll,
  query: {
    deptAuth: 'id',
    status: 1,
  },
})

function returnBack(row) {
  returnRegisterInfo.value.row = row
  returnRegisterInfo.value.visible = true
}
function returnBackMore() {
  modifyInfoReturn.value.type = 'return'
  modifyInfoReturn.value.row = tableInfo.value.selections
  modifyInfoReturn.value.visible = true
}

function selectMonthCallback(data) {
  borrowRecordReturn([{ ...returnRegisterInfo.value.row, ...data }]).then(
    (resp) => {
      if (resp && resp.success) {
        returnRegisterInfo.value.visible = false
        search()
      }
    }
  )
}

function updateCallback() {
  updateBorrowRecordPut(borrowingRegisterInfo.value.row).then((resp) => {
    if (resp && resp.success) {
      borrowingRegisterInfo.value.visible = false
      search()
    }
  })
}
function showProductDetail(row) {
  detailInfo.value.visible = true
  detailInfo.value.id = row.assetId
}
function tableRowOtherClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}

function del(row = undefined) {
  let ids = []

  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.value.selections.map((item) => item.id)
  }
  removeBorrowRecord(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//删除
function remove(row) {
  const data = []
  data.push(row.id)
  removeBorrowRecord(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function specialDelete(row) {
  // 特殊删除
  const data = [row.id]
  specialDeleteAssetCard(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}

// 创建
function create() {
  modifyInfo.value.type = 'create'
  modifyInfo.value.visible = true
  modifyInfo.value.title = '新增借用'
  modifyInfo.value.orderId = null
  modifyInfo.value.canModifyModule = ''
  modifyInfo.value.buildCardData = []
}

function update(row) {
  borrowingRegisterInfo.value.visible = true
  borrowingRegisterInfo.value.row = row
  /*  modifyInfo.value.type = 'update'
  modifyInfo.value.orderId = row.id
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改资产卡片'
  modifyInfo.value.canModifyModule = ''
  modifyInfo.value.buildCardData = [] */
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  let arr = [
    {
      asTbName: 'core_asset,core_asset',
      columnName: 'use_dept_id,depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'assetSourceAuth',
    },
  ]
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
async function getList() {
  tableInfo.value.refresh = Math.random()
}
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  filterInfo.value.query.queryParams.useDeptIdMult = ''
  search()
}
function getCustomize(slipSelect = true) {
  let param = {
    tableKey:
      'assetBorrowRecordList-com.slip.spd.entity.vo.asset.useManage.AssetBorrowRecordVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      filterInfo.value.searchList = [
        ...searchInfo.searchList,
        {
          slot: true,
          value: 'useDeptName',
        },
      ]
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = slipSelect
      tableInfo.value.api = getBorrowRecordPage
      getList()
    }
  })
}
function downloadTemplate() {
  exportTemplateExcel('asset_card_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
function handleClose() {
  dialogInfo.value.visible = false
}
function checkConfirm() {
  print()
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function handelPrint() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = 'page'
}
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetBorrowRecordList',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          printCount: true,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
              ...page.value,
              page: dialogInfo.value.flag === 'page' ? true : false,
            }),
          },
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {},
    callback: printCallback,
    printCount: true,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.value.query,
        ...page.value,
        page: dialogInfo.value.flag === 'page' ? true : false,
      }),
    },
  })
  popoverVisible.value = false
}
function printCallback() {
  /* try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: infoList.value.data.id,
      orderType: 77,
    })
  } catch (error) {} */
}

//导出excel
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: excelBorrowRecord, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function exportExcel() {
  excelPrint.value.type = 'excel'
  excelPrint.value.excel.params = proxy.$fn.deepClone({
    ...proxy.$fn.delEmptyAttribute(filterInfo.value.query),
    ...page.value,
  })
  excelPrint.value.refresh = Math.random()
}
</script>

<style scoped></style>
